﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using YunLuPos.Printer;
using YunLuPos.Utils;

namespace YunLuPos.Printer
{
    public class LPTPrinter : PrintBase
    {
        const uint GENERIC_READ = 0x80000000;
        const uint GENERIC_WRITE = 0x40000000;
        const uint FILE_ATTRIBUTE_NORMAL = 0x80;

        [DllImport("kernel32.dll")]
        public static extern int CreateFile(
          string lpFileName,
          uint dwDesiredAccess,
          int dwShareMode,
          int lpSecurityAttributes,
          int dwCreationDisposition,
          uint dwFlagsAndAttributes,
          int hTemplateFile
          );

        [DllImport("kernel32.dll")]
        public static extern bool WriteFile(
          int hFile,
          byte[] lpBuffer,
          int nNumberOfBytesToWrite,
          ref int lpNumberOfBytesWritten,
          int lpOverlapped
          );

        [DllImport("kernel32.dll")]
        public static extern bool DefineDosDevice(
        int dwFlags,
        string lpDeviceName,
        string lpTargetPath);

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(
          int hObject
          );
        [DllImport("kernel32.dll")]
        public static extern bool ReadFile(
          int hFile,
          byte[] lpBuffer,
          int nNumberOfBytesToRead,
          ref int lpNumberOfBytesRead,
          int lpOverlapped
          );


        private int iHandle = -1;
        public string LPT_PORT = "LPT_PORT";

        public override bool Dispose()
        {
            if (iHandle != -1)
            {
                return CloseHandle(iHandle);
            }
            return true;
        }

        public override bool initPrinter()
        {
            LPT_PORT = InIUtil.ReadInIData(InIUtil.PrintSection,InIUtil.LptProt);
            iHandle = CreateFile(@"\\.\" + LPT_PORT, GENERIC_READ | GENERIC_WRITE, 0, 0, 3, 0, 0);
            Console.WriteLine(iHandle);
            if (iHandle != -1)
                return true;
            return false;
        }

        public override bool NewRow()
        {
             byte[] temp = new byte[] { 0x0A };
            return write(temp);
        }

        public override bool open()
        {
            return true;
        }

        public override bool write(byte[] b)
        {
            int i = 0;
            WriteFile(iHandle, b, b.Length, ref i, 0);
            return true;
        }
    }
}
